<?php
/**
 * Created by PhpStorm.
 * User: chenxiang
 * Date: 2017/4/26
 * Time: 12:54
 */

namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use App\Model\Admin;
use App\Model\Env;
use App\Model\Json;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Unikent\Curl\Curl;

class InitController extends Controller
{

    public function index(){
        $env = Env::getFile('.env');
        $conf = $env;
        return view('Home/Init/Index',compact('conf'));
    }

    public function Init(Request $request){
        $data = $request->all();
        // 修改 配置文件·
        Env::setFile($data,'.env');
        Env::Save($data,'.env');
        $curl = new Curl();
        $curl->create(action('Home\InitController@migrate'));
        $data = json_decode($curl->execute(),true);
        if(!$data['status']){
//            exec('rm -f '.$this->getInit(),$exec);
            dd($data);
        }
        return redirect('/');
    }



    public function migrate(){
        $status = 0;
        // 请求 数据迁移方法
        exec('cd '.base_path().' && php artisan migrate',$exec);
        foreach($exec as $val){
            $status = preg_match('/.*?(SQLSTATE).*?/',$val);
            if($status)break;
        }
        // 判断是否出错
        if(!($status)){
            // 为出错 则 允许 数据迁移
            exec('cd '.base_path().' && php artisan db:seed --class=InitWeb ',$exec);
            foreach($exec as $val){
                $status = preg_match('/(.*?(SQLSTATE).*?)|(.*?(Error|ERROR).*?)/',$val);
                if($status)break;
            }
        }
        if($status){
            return Json::error($exec);
        }else{
            $this->InitOut();
            return Json::success('成功');
        }
    }

    // 运行 成功 注释 路由中的 初始化控制器
    protected function InitOut(){
        $file = Env::File('/routes/web.php');

//        $file = collect(file(base_path().DIRECTORY_SEPARATOR.'/routes/web.php',FILE_IGNORE_NEW_LINES));
        $file->transform(function($item){
            if(preg_match('/.*?require(.*?Init.php.*?).*?/',$item)){
                return '//'.$item;
            }
            return $item;
        });
        Env::Save($file,'/routes/web.php');
//        $str = "
//";
//        $conf = implode($str,$file->toArray());
//        \File::put(base_path().DIRECTORY_SEPARATOR.'/routes/web.php',$conf);
    }

}